import React, {Component} from "react";
import PubSub from "pubsub-js";

export default class Footer extends Component{
    state={mainList:[]}
    componentDidMount() {
        console.log('foot挂载了')
        this.updateMainList=PubSub.subscribe('updateMainList',(_,mainList)=>{
            this.setState({mainList:mainList})
        })
    }

    //删除已完成任务
    removeAllDone=()=>{
        //选出需要删除的任务id
        let needDeleteDoneIds=this.state.mainList.filter(item=>item.done).map(item=>item.id)
        PubSub.publish('needDeleteDoneIds',needDeleteDoneIds)
    }
    //更新全部done状态
    handleUpdate=(e)=> {
        let updateAllListDone = this.state.mainList.filter(item => item.done !== e.target.checked).map(item => item.id)
        PubSub.publish('updateAllListDone',{changeIds:updateAllListDone,checked:e.target.checked})
    }

    //移除事件订阅
  componentWillUnmount() {
        PubSub.unsubscribe(this.updateMainList)
  }

    render(){
        const {mainList}=this.state
        let checkedAll=mainList.reduce((pre,cur,index,arr)=>{
            // console.log(index.js,arr)
            return cur.done?pre+=1:pre+=0
        },0)
        return (
            <div className="todo-footer">
                <label>
                    <input type="checkbox" checked={checkedAll===mainList.length&&checkedAll!==0?true:false} onChange={(e)=>this.handleUpdate(e)}/>
                </label>
                <span><span>已完成{checkedAll}</span> / 全部{mainList.length}</span>
                <button className="btn btn-danger" onClick={this.removeAllDone}>清除已完成任务</button>
            </div>
        )
    }

}
